package helper

import (
	"fmt"
	"github.com/redis/go-redis/v9"
	"time"
)

var Redis *redis.Client

func InitRedis() {
	if r := Configer.GetBool("isEnableRedis"); !r {
		fmt.Println("初始化 redis 失败：配置关闭")
		Redis = nil
		return
	}
	rdb := redis.NewClient(
		&redis.Options{
			Network:         Configer.GetString("redis.network"),
			Addr:            Configer.GetString("redis.host") + ":" + Configer.GetString("redis.port"),
			ClientName:      Configer.GetString("redis.collectionName"),
			Username:        Configer.GetString("redis.username"),
			Password:        Configer.GetString("redis.password"),
			DB:              Configer.GetInt("redis.dbNumber"),
			MaxRetries:      Configer.GetInt("redis.maxRetries"),
			MinRetryBackoff: parseDurationFromString(Configer.GetString("redis.minRetryBackoff") + "us"),
			MaxRetryBackoff: parseDurationFromString(Configer.GetString("redis.maxRetryBackoff") + "us"),
			DialTimeout:     parseDurationFromString(Configer.GetString("redis.dialTimeout") + "s"),
			ReadTimeout:     parseDurationFromString(Configer.GetString("redis.readTimeout") + "s"),
			WriteTimeout:    parseDurationFromString(Configer.GetString("redis.writeTimeout") + "s"),
			PoolFIFO:        Configer.GetBool("redis.poolFIFO"),
			PoolSize:        Configer.GetInt("redis.poolSize"),
			PoolTimeout:     parseDurationFromString(Configer.GetString("redis.poolTimeout") + "s"),
			MinIdleConns:    Configer.GetInt("redis.minIdleConns"),
			MaxIdleConns:    Configer.GetInt("redis.maxIdleConns"),
			ConnMaxIdleTime: parseDurationFromString(Configer.GetString("redis.connMaxIdleTime") + "s"),
		})
	Redis = rdb
}

func parseDurationFromString(duration string) time.Duration {
	//fmt.Println(duration)
	if d, err := time.ParseDuration(duration); err != nil {
		panic("初始化 redis 失败：" + err.Error())
	} else {
		return d
	}
}
